package com.nd.te.pro;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.junit.runner.Result;

import java.io.IOException;

public class process {


    public static class datamapper extends Mapper<LongWritable, Text, Text, data>{
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, data>.Context context) throws IOException, InterruptedException {
            String line = new String(value.getBytes(),0,value.getLength(),"UTF-8");
            String[] split = line.split(",");
            if (split.length == 9 && Integer.parseInt(split[0]) >= 2010 && Integer.parseInt(split[0])<2020) {
                data d = new data(Integer.parseInt(split[0]),Integer.parseInt(split[1]),split[2],split[3],split[4],split[5],Double.parseDouble(split[6]),Double.parseDouble(split[7]),Integer.parseInt(split[8]));
                context.write(new Text(d.getCountry()), d);
            }
        }
    }

    public static class datareducer extends Reducer<Text, data, String, result>{
        protected void reduce(Text key, Iterable<data> values, Context context) throws IOException, InterruptedException{
            int count = 0;
            int sum = 0;
            String country = new String();
            for(data d:values){
                count++;
                sum+=d.getAttack();
                country=d.getCountry();
            }
            context.write(country, new result(country, count, sum));
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        //args=new String[]{"hdfs://hadoop101:8020/wc/input/data.txt","hdfs://hadoop101:8020/wc/datapro1.txt"};

        args = new String[]{"C:\\Users\\张传畅\\Desktop\\bigwork\\data.txt", "C:\\Users\\张传畅\\Desktop\\bigwork\\out.txt"};

        Configuration conf=new Configuration();

        Job job = Job.getInstance(conf);

        job.setJarByClass(process.class);

        job.setMapperClass(datamapper.class);
        job.setReducerClass(datareducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(data.class);

        job.setOutputKeyClass(String.class);
        job.setOutputValueClass(Result.class);

        FileInputFormat.addInputPath(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));

        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : 1);
    }
}